package com.example.demo02.utils;

import cn.hutool.core.util.StrUtil;
import com.example.demo02.dto.HttpPostBaseObject;
import com.example.demo02.exception.BusinessException;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;




/**
 * Created by Ricy on 2017/7/10.
 */
@Slf4j
public class HttpUtil {
    public  static  Integer CONNECT_TIMEOUT=30000;

    /**
     * http请求
     *
     * @param requestUrl         请求路径
     * @param httpPostBaseObject 请求对象
     * @param convertClass       响应对象类型
     * @return {@link T} 响应对象
     */
    public static <T> T httpPost(String requestUrl, HttpPostBaseObject httpPostBaseObject, Class<T> convertClass) {
        HttpPost httpPost = new HttpPost(requestUrl);
        String content = httpPostBaseObject.toRequestContent();
        log.info("请求参数: {}", content);
        StringEntity se = new StringEntity(content, "UTF-8");
        se.setContentType("application/json");
        httpPost.setEntity(se);
        httpPost.addHeader("Content-Type", "application/json");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECT_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            String result = EntityUtils.toString(httpResponse.getEntity());
            return com.alibaba.fastjson.JSONObject.parseObject(result, convertClass);
        } catch (Exception e) {
            log.error(StrUtil.format("发送http请求时发生错误, 请求参数:{}, 报错信息:[{}]", httpPostBaseObject.toRequestContent(), e.getMessage()), e);
            throw new BusinessException("发送http请求时发生错误");
        }
    }

}
